package com.rookie.im.common.annotation;

import org.apache.commons.lang3.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.regex.Pattern;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Constraint(
        validatedBy = {MobileValidator.class}
)
public @interface IsMobile {
    // 是否必填
    boolean required() default true;

    // 提示信息
    String message() default "手机号码格式错误";

    // 下面两个属性必须添加

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

class MobileValidator implements ConstraintValidator<IsMobile, String> {
    static final Pattern MOBILE_PATTERN = Pattern.compile ("^0{0,1}(1[0-9][0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StringUtils.isEmpty(value)) {
            return true;
        }
        return MOBILE_PATTERN.matcher(value).matches();
    }
}
